// ===== 导入模块 =====
const { ipcRenderer, clipboard } = require('electron');
const path = require('path');
const fs = require('fs');

// ===== 全局变量 =====
let store;
let currentFiles = [];
let mediaFiles = [];
let isAscending = false;
let currentFileIndex = -1;
// 添加全局变量
let favoriteFiles = []; // 存储收藏的文件路径
// 添加待删除文件列表
let toDeleteFiles = [];
let currentPath = '';
let lastClipboardContent = clipboard.readText();
// 改用单一数组和额外的状态变量
let allFiles = []; // 所有文件
let filteredFiles = []; // 经过筛选的文件
let currentFileType = 'all';
// 文件类型定义
const fileTypes = {
    video: ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv'],
    image: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'],
};

// ===== DOM 元素获取 =====
const pathInput = document.getElementById('pathInput');
const scanBtn = document.getElementById('scanBtn');
const fileList = document.getElementById('fileList');
const sortType = document.getElementById('sortType');
const fileType = document.getElementById('fileType');
const sortOrderBtn = document.getElementById('sortOrderBtn');
const minimizeBtn = document.getElementById('minimizeBtn');
const maximizeBtn = document.getElementById('maximizeBtn');
const closeBtn = document.getElementById('closeBtn');
const prevFileBtn = document.getElementById('prevFile');
const nextFileBtn = document.getElementById('nextFile');
const currentFileName = document.getElementById('currentFileName');
const clipboardDialog = document.getElementById('clipboardDialog');
const clipboardPathElement = document.getElementById('clipboardPath');
const useClipboardBtn = document.getElementById('useClipboardBtn');
const cancelClipboardBtn = document.getElementById('cancelClipboardBtn');
const modal = document.getElementById('fileModal');
const modalContent = document.getElementById('modalContent');
const closeModal = document.querySelector('.close-modal');
// 在 DOM 元素获取部分添加
const setFoldersBtn = document.getElementById('setFoldersBtn');
const foldersDialog = document.getElementById('foldersDialog');
const currentFoldersInfo = document.getElementById('currentFoldersInfo');
// const deleteVideoBtn = document.getElementById('deleteVideoBtn');
// const collectVideoBtn = document.getElementById('collectVideoBtn');
let isMaximized = false;
// ===== 初始化函数 =====

// deleteVideoBtn.addEventListener('click', async () => {
//     const filePath = mediaFiles[currentFileIndex].path;
//     const deletePath = await ipcRenderer.invoke('store-get', 'deleteFolderPath');
    
//     if (!deletePath) {
//         alert('请先设置Delete文件夹路径');
//         return;
//     }

//     // 直接调用文件移动功能
//     ipcRenderer.invoke('move-file', {
//         filePath: filePath,
//         targetFolder: deletePath,
//         type: 'delete'
//     }).then(() => {
//         // 从媒体文件列表中移除该文件
//         mediaFiles.splice(currentFileIndex, 1);
//         // 关闭模态框
//         closeModalHandler();
//         // 更新文件列表显示
//         sortAndFilterFiles();
//     });
// });

// collectVideoBtn.addEventListener('click', async () => {
//     const filePath = mediaFiles[currentFileIndex].path;
//     const likePath = await ipcRenderer.invoke('store-get', 'likeFolderPath');
    
//     if (!likePath) {
//         alert('请先设置Like文件夹路径');
//         return;
//     }

//     // 直接调用文件移动功能
//     ipcRenderer.invoke('move-file', {
//         filePath: filePath,
//         targetFolder: likePath,
//         type: 'like'
//     }).then(() => {
//         // 从媒体文件列表中移除该文件
//         mediaFiles.splice(currentFileIndex, 1);
//         // 关闭模态框
//         closeModalHandler();
//         // 更新文件列表显示
//         sortAndFilterFiles();
//     });
// });


// ===== 工具函数 =====
function isValidPath(path) {
    try {
        return fs.existsSync(path) && fs.statSync(path).isDirectory();
    } catch (error) {
        return false;
    }
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function formatDate(date) {
    return new Date(date).toLocaleString();
}

function getFileType(filename) {
    const ext = filename.toLowerCase().slice(filename.lastIndexOf('.'));
    if (fileTypes.video.includes(ext)) return 'video';
    if (fileTypes.image.includes(ext)) return 'image';
    return 'other';
}

// ===== 文件处理函数 =====
function sortAndFilterFiles() {
    // 根据类型过滤文件
    filteredFiles = allFiles.filter(file => {
        if (fileType.value === 'all') return true;
        const ext = file.name.toLowerCase().slice(file.name.lastIndexOf('.'));
        if (fileType.value === 'video') return fileTypes.video.includes(ext);
        if (fileType.value === 'image') return fileTypes.image.includes(ext);
        return !fileTypes.video.includes(ext) && !fileTypes.image.includes(ext);
    });
    
    // 文件排序
    filteredFiles.sort((a, b) => {
        let compareResult = 0;
        switch (sortType.value) {
            case 'name':
                compareResult = a.name.localeCompare(b.name);
                break;
            case 'size':
                compareResult = a.size - b.size;
                break;
            case 'mtime':
                compareResult = new Date(a.mtime) - new Date(b.mtime);
                break;
            case 'ctime':
                compareResult = new Date(a.ctime) - new Date(b.ctime);
                break;
        }
        return isAscending ? compareResult : -compareResult;
    });
    
    displayFiles(filteredFiles);
}

// ===== 事件监听器绑定 =====
document.addEventListener('DOMContentLoaded', async () => {
    setTimeout(checkClipboard, 500);
    favoriteFiles = [];
    initializeFavoritePanel();
    // 初始化删除面板
    initializeDeletePanel();
    startClipboardMonitoring();
    // 设置文件夹按钮事件
    setFoldersBtn.addEventListener('click', async () => {
        const paths = await ipcRenderer.invoke('set-folder-paths');
        if (paths) {
            updateFoldersInfo(paths);
        }
    });

    // 初始化显示当前文件夹信息
    const initialPaths = await ipcRenderer.invoke('get-folder-paths');
    updateFoldersInfo(initialPaths);
    // 绑定按钮事件
    scanBtn.addEventListener('click', () => {
        const path = pathInput.value.trim();
        if (!path) {
            alert('请输入有效的文件路径！');
            return;
        }
        currentPath = path;
        
        // 更新最近使用的路径
        ipcRenderer.send('update-recent-paths', path);
        
        ipcRenderer.send('scan-directory', path);
        fileList.innerHTML = '<div class="file-item">正在扫描中...</div>';
    });

    sortType.addEventListener('change', sortAndFilterFiles);
    fileType.addEventListener('change', sortAndFilterFiles);
    sortOrderBtn.addEventListener('click', () => {
        isAscending = !isAscending;
        sortOrderBtn.textContent = isAscending ? '↑ 升序' : '↓ 降序';
        sortAndFilterFiles();
    });
    
    // ... 其他事件监听器绑定
    // 模态框关闭按钮事件
    closeModal.addEventListener('click', closeModalHandler);
    
    // 点击模态框外部区域关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            closeModalHandler();
        }
    });

    // ESC 键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && modal.style.display === 'flex') {
            closeModalHandler();
        }
    });

    // 上一个/下一个文件按钮事件
    prevFileBtn.addEventListener('click', () => {
        if (currentFileIndex > 0) {
            currentFileIndex--;
            showModal(filteredFiles[currentFileIndex]);
        }
    });

    nextFileBtn.addEventListener('click', () => {
        if (currentFileIndex < filteredFiles.length - 1) {
            currentFileIndex++;
            showModal(filteredFiles[currentFileIndex]);
        }
    });

    // 左右方向键导航
    document.addEventListener('keydown', (e) => {
        if (modal.style.display !== 'block') return;
    
        if (e.key === 'ArrowLeft' && currentFileIndex > 0) {
            currentFileIndex--;
            showModal(filteredFiles[currentFileIndex]);
        } else if (e.key === 'ArrowRight' && currentFileIndex < filteredFiles.length - 1) {
            currentFileIndex++;
            showModal(filteredFiles[currentFileIndex]);
        }
    });

    // 剪贴板对话框按钮事件
    useClipboardBtn.addEventListener('click', useClipboardPath);
    cancelClipboardBtn.addEventListener('click', () => {
        clipboardDialog.style.display = 'none';
    });

    // 添加文档区域的右键点击事件监听
    document.addEventListener('contextmenu', (event) => {
        // 检查点击的元素是否是文件项
        const fileItem = event.target.closest('.file-item'); // 假设文件项有 .file-item 类
        
        if (fileItem) {
            // 如果点击的是文件项，发送文件相关的上下文菜单请求
            const filePath = fileItem.dataset.path; // 假设文件路径存储在 data-path 属性中
            ipcRenderer.send('show-context-menu', {
                type: 'file',
                filePath: filePath
            });
        } else {
            // 如果点击的是其他区域，发送通用上下文菜单请求
            ipcRenderer.send('show-context-menu', {
                type: 'general'
            });
        }
    });
});

// ===== IPC 通信处理 =====
ipcRenderer.on('scan-result', (event, files) => {
    if (files.error) {
        fileList.innerHTML = `<div class="file-item error">${files.error}</div>`;
        return;
    }
    allFiles = files;
    sortAndFilterFiles();
});

ipcRenderer.on('show-file-info', (event, filePath) => {
    showFileInfo(filePath);
});

// 添加最大化/还原按钮点击事件
// 监听窗口状态变化
ipcRenderer.on('window-state', (event, isMaximized) => {
    isWindowMaximized = isMaximized;
    // 根据窗口状态更改图标
    if (isMaximized) {
        console.log('最大化');
    } else {
        console.log('还原');
    }
});

// 修改最大化按钮点击事件
maximizeBtn.addEventListener('click', () => {
    ipcRenderer.send('window-control', 'maximize');
});

minimizeBtn.addEventListener('click', () => {
    ipcRenderer.send('window-control', 'minimize');
});
closeBtn.addEventListener('click', () => {
    ipcRenderer.send('window-control', 'hide');
});
// 监听文件移动事件
ipcRenderer.on('file-moved', (event, data) => {
    // 从当前显示的文件列表中移除已移动的文件
    const fileItem = document.querySelector(`[data-path="${data.originalPath}"]`);
    if (fileItem) {
        fileItem.remove();
    }
    
    // 可以根据需要更新UI
    sortAndFilterFiles();
});
// 监听标记为删除的消息
ipcRenderer.on('mark-for-delete', (event, filePath) => {
    // 从数组中查找文件信息
    const file = allFiles.find(f => f.path === filePath);
    if (file) {
        addToDeleteList({
            name: file.name,
            path: file.path
        });
    } else {
        // 如果找不到文件信息，使用路径创建基本信息
        const fileName = filePath.split(/[\\/]/).pop();
        addToDeleteList({
            name: fileName,
            path: filePath
        });
    }
});
// 添加到删除列表
function addToDeleteList(file) {
    // 检查是否已经存在
    if (!toDeleteFiles.some(f => f.path === file.path)) {
        toDeleteFiles.push(file);
        updateDeleteList();
        
        // 添加高亮样式
        const fileElement = document.querySelector(`.file-item[data-path="${file.path.replace(/\\/g, '/')}"]`);
        if (fileElement) {
            fileElement.classList.add('marked-delete');
        }
        
        showNotification('已标记为删除');
    } else {
        showNotification('该文件已在删除列表中');
    }
}
// 更新删除列表显示
function updateDeleteList() {
    const deletePanel = document.getElementById('deletePanel');
    const deleteList = document.getElementById('deleteList');
    
    if (deletePanel && deleteList) {
        deleteList.innerHTML = toDeleteFiles.map(file => `
            <div class="delete-item" data-path="${file.path}">
                <span class="delete-name">${file.name}</span>
                <button class="remove-delete">×</button>
            </div>
        `).join('');
        
        // 更新删除面板显示
        deletePanel.style.display = toDeleteFiles.length > 0 ? 'block' : 'none';
        
        // 添加移除按钮事件
        deleteList.querySelectorAll('.remove-delete').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const item = e.target.closest('.delete-item');
                const filePath = item.dataset.path;
                
                // 从删除列表中移除
                toDeleteFiles = toDeleteFiles.filter(f => f.path !== filePath);
                
                // 移除主界面中的标记
                const mainFileEl = document.querySelector(`.file-item[data-path="${filePath.replace(/\\/g, '/')}"]`);
                if (mainFileEl) {
                    mainFileEl.classList.remove('marked-delete');
                }
                
                // 移除重复文件对话框中的标记（如果存在）
                const duplicateFileEl = document.querySelector(`.duplicate-file[data-path="${filePath.replace(/\\/g, '/')}"]`);
                if (duplicateFileEl) {
                    duplicateFileEl.classList.remove('marked-delete');
                }
                
                // 更新删除列表
                updateDeleteList();
                
                // 保存更新
                ipcRenderer.send('update-to-delete', toDeleteFiles);
                
                showNotification('已从删除列表中移除', 'success');
            });
        });
    }
}
// 从删除列表中移除
function removeFromDeleteList(index) {
    const removedFile = toDeleteFiles[index];
    toDeleteFiles.splice(index, 1);
    
    // 移除高亮样式
    const fileElement = document.querySelector(`.file-item[data-path="${removedFile.path.replace(/\\/g, '/')}"]`);
    if (fileElement) {
        fileElement.classList.remove('marked-delete');
    }
    
    updateDeleteList();
    showNotification('已从删除列表中移除');
}
// 初始化删除面板
function initializeDeletePanel() {
    const confirmBtn = document.getElementById('confirmDelete');
    const cancelBtn = document.getElementById('cancelDelete');
    
    confirmBtn.addEventListener('click', async () => {
        if (toDeleteFiles.length === 0) {
            showNotification('删除列表为空', 'info');
            return;
        }
        
        // 显示确认对话框
        const confirmResult = await showConfirmDialog(
            '确认删除',
            `是否将 ${toDeleteFiles.length} 个文件移动到 Delete 文件夹？`
        );
        
        if (confirmResult) {
            // 显示加载提示
            showNotification('正在移动文件...', 'info');
            
            // 移动文件到 Delete 文件夹
            const result = await moveFilesToDeleteFolder();
            
            // 显示结果
            if (result.success > 0) {
                showNotification(
                    `成功移动 ${result.success} 个文件` + 
                    (result.fail > 0 ? `，${result.fail} 个失败` : ''),
                    result.fail > 0 ? 'warning' : 'info'
                );
            } else {
                showNotification('没有文件被移动', 'error');
            }
            
            // 清空删除列表
            toDeleteFiles = [];
            updateDeleteList();
            
            // 隐藏面板
            document.getElementById('deletePanel').style.display = 'none';
            
            // 移除所有文件的删除标记
            document.querySelectorAll('.file-item.marked-delete').forEach(item => {
                item.classList.remove('marked-delete');
            });
        }
    });
    
    cancelBtn.addEventListener('click', () => {
        toDeleteFiles = [];
        updateDeleteList();
        document.getElementById('deletePanel').style.display = 'none';
        // 移除所有文件的删除标记
        document.querySelectorAll('.file-item.marked-delete').forEach(item => {
            item.classList.remove('marked-delete');
        });
        showNotification('已取消删除标记');
    });
}
// 移动文件到 Delete 文件夹
async function moveFilesToDeleteFolder() {
    const { ipcRenderer } = require('electron');
    
    // 获取 Delete 文件夹路径
    const folderPaths = await ipcRenderer.invoke('get-folder-paths');
    const deletePath = folderPaths.deletePath;
    
    if (!deletePath) {
        showNotification('请先设置 Delete 文件夹路径', 'error');
        return false;
    }
    
    let successCount = 0;
    let failCount = 0;
    
    // 使用 Promise.all 同时处理所有文件移动
    await Promise.all(toDeleteFiles.map(async (file) => {
        try {
            const result = await ipcRenderer.invoke('move-file', {
                filePath: file.path,
                targetFolder: deletePath,
                type: 'delete'
            });
            
            if (result) {
                successCount++;
            } else {
                failCount++;
            }
        } catch (error) {
            console.error('移动文件失败:', error);
            failCount++;
        }
    }));
    
    // 返回移动结果
    return {
        success: successCount,
        fail: failCount
    };
}
// 添加确认对话框函数
function showConfirmDialog(title, message) {
    return new Promise((resolve) => {
        const dialog = document.createElement('div');
        dialog.className = 'dialog';
        dialog.style.display = 'flex';
        dialog.innerHTML = `
            <div class="dialog-content">
                <h3>${title}</h3>
                <p>${message}</p>
                <div class="dialog-buttons">
                    <button class="btn confirm-btn">确认</button>
                    <button class="btn cancel-btn">取消</button>
                </div>
            </div>
        `;

        document.body.appendChild(dialog);

        const confirmBtn = dialog.querySelector('.confirm-btn');
        const cancelBtn = dialog.querySelector('.cancel-btn');

        confirmBtn.addEventListener('click', () => {
            dialog.remove();
            resolve(true);
        });

        cancelBtn.addEventListener('click', () => {
            dialog.remove();
            resolve(false);
        });
    });
}
// 添加一个移动文件到 Like 文件夹的函数
async function moveFilesToLikeFolder() {
    const { ipcRenderer } = require('electron');
    
    // 获取 Like 文件夹路径
    const folderPaths = await ipcRenderer.invoke('get-folder-paths');
    const likePath = folderPaths.likePath;
    
    if (!likePath) {
        showNotification('请先设置 Like 文件夹路径', 'error');
        return false;
    }

    let successCount = 0;
    let failCount = 0;

    // 使用 Promise.all 同时处理所有文件移动
    await Promise.all(favoriteFiles.map(async (file) => {
        try {
            const result = await ipcRenderer.invoke('move-file', {
                filePath: file.path,
                targetFolder: likePath,
                type: 'like'
            });
            
            if (result) {
                successCount++;
            } else {
                failCount++;
            }
        } catch (error) {
            console.error('移动文件失败:', error);
            failCount++;
        }
    }));

    // 返回移动结果
    return {
        success: successCount,
        fail: failCount
    };
}
// 初始化收藏面板
function initializeFavoritePanel() {
    const confirmBtn = document.getElementById('confirmFavorites');
    const cancelBtn = document.getElementById('cancelFavorites');

    confirmBtn.addEventListener('click', async () => {
        if (favoriteFiles.length === 0) {
            showNotification('收藏列表为空', 'info');
            return;
        }

        // 显示确认对话框
        const confirmResult = await showConfirmDialog(
            '确认移动',
            `是否将 ${favoriteFiles.length} 个文件移动到 Like 文件夹？`
        );

        if (confirmResult) {
            // 显示加载提示
            showNotification('正在移动文件...', 'info');
            
            // 移动文件
            const result = await moveFilesToLikeFolder();
            
            // 显示结果
            if (result.success > 0) {
                showNotification(
                    `成功移动 ${result.success} 个文件` + 
                    (result.fail > 0 ? `，${result.fail} 个失败` : ''),
                    result.fail > 0 ? 'warning' : 'info'
                );
            } else {
                showNotification('没有文件被移动', 'error');
            }

            // 清空收藏列表
            favoriteFiles = [];
            updateFavoriteList();
            
            // 隐藏面板
            document.getElementById('favoritePanel').style.display = 'none';
            
            // 移除所有文件的收藏高亮
            document.querySelectorAll('.file-item.favorited').forEach(item => {
                item.classList.remove('favorited');
            });
        }
    });

    cancelBtn.addEventListener('click', () => {
        favoriteFiles = [];
        updateFavoriteList();
        document.getElementById('favoritePanel').style.display = 'none';
        // 移除所有文件的收藏高亮
        document.querySelectorAll('.file-item.favorited').forEach(item => {
            item.classList.remove('favorited');
        });
        showNotification('已取消收藏');
    });
}

// 更新收藏列表显示
function updateFavoriteList() {
    const favoritePanel = document.getElementById('favoritePanel');
    const favoriteList = document.getElementById('favoriteList');
    
    if (favoritePanel && favoriteList) {
        favoriteList.innerHTML = favoriteFiles.map(file => `
            <div class="favorite-item" data-path="${file.path}">
                <span class="favorite-name">${file.name}</span>
                <button class="remove-favorite">×</button>
            </div>
        `).join('');
        
        // 更新收藏面板显示
        favoritePanel.style.display = favoriteFiles.length > 0 ? 'block' : 'none';
        
        // 添加移除按钮事件
        favoriteList.querySelectorAll('.remove-favorite').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const item = e.target.closest('.favorite-item');
                const filePath = item.dataset.path;
                
                // 从收藏列表中移除
                favoriteFiles = favoriteFiles.filter(f => f.path !== filePath);
                
                // 移除主界面中的标记
                const mainFileEl = document.querySelector(`.file-item[data-path="${filePath.replace(/\\/g, '/')}"]`);
                if (mainFileEl) {
                    mainFileEl.classList.remove('marked-favorite');
                }
                
                // 移除重复文件对话框中的标记（如果存在）
                const duplicateFileEl = document.querySelector(`.duplicate-file[data-path="${filePath.replace(/\\/g, '/')}"]`);
                if (duplicateFileEl) {
                    duplicateFileEl.classList.remove('marked-favorite');
                }
                
                // 更新收藏列表
                updateFavoriteList();
                
                // 保存更新
                ipcRenderer.send('update-favorites', favoriteFiles);
                
                showNotification('已从收藏中移除', 'success');
            });
        });
    }
}
// 添加收藏
function addToFavorites(file) {
    // 检查是否已经存在
    if (!favoriteFiles.some(f => f.path === file.path)) {
        favoriteFiles.push(file);
        updateFavoriteList();
        
        // 显示收藏面板
        const favoritePanel = document.getElementById('favoritePanel');
        favoritePanel.style.display = 'block';
        
        // 添加高亮样式
        const fileElement = document.querySelector(`.file-item[data-path="${file.path.replace(/\\/g, '/')}"]`);
        if (fileElement) {
            fileElement.classList.add('favorited');
        }
        
        showNotification('已添加到收藏列表');
    } else {
        showNotification('该文件已在收藏列表中');
    }
}
// 移除收藏
function removeFavorite(index) {
    const removedFile = favoriteFiles[index];
    favoriteFiles.splice(index, 1);
    updateFavoriteList();
    
    // 移除高亮样式
    const fileElement = document.querySelector(`.file-item[data-path="${removedFile.path.replace(/\\/g, '/')}"]`);
    if (fileElement) {
        fileElement.classList.remove('favorited');
    }
    
    showNotification('已从收藏列表中移除');
}
function renderFileList(files) {
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = files.map(file => `
        <div class="file-item" data-path="${file.path.replace(/\\/g, '/')}" data-type="${getFileType(file.name)}">
            <span>${file.name}</span>
            <!-- 其他文件信息 -->
        </div>
    `).join('');
    
    // 更新全局文件列表
    allFiles = files;
}
// 添加一个简单的通知函数
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 2000);
}
// ... 其他 IPC 处理函数
// 监听来自主进程的添加收藏消息
ipcRenderer.on('add-to-favorites', (event, filePath) => {
    // 从数组中查找文件信息
    const file = allFiles.find(f => f.path === filePath);
    if (file) {
        addToFavorites({
            name: file.name,
            path: file.path
        });
    } else {
        // 如果找不到文件信息，使用路径创建基本信息
        const fileName = filePath.split(/[\\/]/).pop(); // 从路径中提取文件名
        addToFavorites({
            name: fileName,
            path: filePath
        });
    }
});

// 新增函数：更新文件高亮
function updateFileHighlight() {
    // 移除所有高亮
    document.querySelectorAll('.file-item').forEach(item => {
        item.classList.remove('current-file');
    });
    
    // 如果有当前文件，添加高亮并滚动
    if (currentFileIndex >= 0 && filteredFiles[currentFileIndex]) {
        const currentFilePath = filteredFiles[currentFileIndex].path;    
        // 使用规范化的路径进行比较
        const normalizedPath = currentFilePath.replace(/\\/g, '/');
        const currentFileElement = document.querySelector(`.file-item[data-path="${normalizedPath}"]`);
        
        if (currentFileElement) {
            currentFileElement.classList.add('current-file');
            // 添加平滑滚动
            currentFileElement.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'center' 
            });
        }
    }
}
// ===== 模态框相关函数 =====
// 修改 showModal 函数
function showModal(file) {
    showFileContent(file);
    modal.style.display = 'flex';
    
    // 更新导航按钮状态
    prevFileBtn.disabled = currentFileIndex <= 0;
    nextFileBtn.disabled = currentFileIndex >= filteredFiles.length - 1;
    
    // 更新文件名显示
    currentFileName.textContent = file.name;
    
    // 立即更新高亮显示
    updateFileHighlight();
}

function showFileContent(file) {
    const type = getFileType(file.name);
    let content = '';
    
    switch(type) {
        case 'video':
            content = `
                <video controls autoplay>
                    <source src="${file.path}" type="video/mp4">
                    您的浏览器不支持视频播放
                </video>
            `;
            break;
        case 'image':
            content = `<img src="${file.path}" alt="图片预览">`;
            break;
        default:
            content = `<div class="unsupported-file">不支持预览此类型文件</div>`;
    }
    
    modalContent.innerHTML = content;
    currentFileName.textContent = file.name;
    
    prevFileBtn.disabled = currentFileIndex <= 0;
    nextFileBtn.disabled = currentFileIndex >= mediaFiles.length - 1;
}

function closeModalHandler() {
    modal.style.display = 'none';
    modalContent.innerHTML = '';
    currentFileIndex = -1;
    mediaFiles = [];
}

// ===== 剪贴板相关函数 =====
function checkClipboard() {
    const clipText = clipboard.readText().trim();
    
    if (clipText && isValidPath(clipText)) {
        clipboardPathElement.textContent = clipText;
        clipboardDialog.style.display = 'flex';
    }
}

function useClipboardPath() {
    const clipText = clipboard.readText().trim();
    if (clipText && isValidPath(clipText)) {
        pathInput.value = clipText;
        currentPath = clipText;
        ipcRenderer.send('scan-directory', clipText);
    }
    clipboardDialog.style.display = 'none';
}
function startClipboardMonitoring() {
    // 初始化上一次剪贴板内容
    lastClipboardContent = clipboard.readText().trim();
    
    // 定期检查剪贴板变化
    setInterval(() => {
        const currentContent = clipboard.readText().trim();
        
        // 只在内容变化且为有效路径时显示对话框
        if (currentContent !== lastClipboardContent && isValidPath(currentContent)) {
            lastClipboardContent = currentContent;
            clipboardPathElement.textContent = currentContent;
            clipboardDialog.style.display = 'flex';
        }
    }, 1000); // 每秒检查一次
}



// ===== 文件列表显示函数 =====

function displayFiles(files) {
    const parentPath = path.dirname(currentPath);
    let html = '';
    
    if (currentPath) {
        html += `
            <div class="file-item" data-type="parent-dir" data-path="${parentPath}">
                <div class="file-info">
                    <div>📁 ..</div>
                    <div class="file-meta">返回上级目录</div>
                </div>
            </div>
        `;
    }
    
    html += files.map((file) => `
        <div class="file-item" 
             data-type="${file.isDirectory ? 'directory' : getFileType(file.name)}" 
             data-path="${file.path.replace(/\\/g, '/')}"
             data-name="${file.name}">
            <div class="file-info">
                <div>${file.isDirectory ? '📁' : '📄'} ${file.name}</div>
                <div class="file-meta">
                    大小: ${formatFileSize(file.size)} | 
                    修改时间: ${formatDate(file.mtime)} | 
                    创建时间: ${formatDate(file.ctime)}
                </div>
            </div>
        </div>
    `).join('');
    
    fileList.innerHTML = html;
    
    // 重新绑定文件点击事件
    const fileItems = document.querySelectorAll('.file-item');
    fileItems.forEach(item => {
        // 移除旧的事件监听器（如果有的话）
        const newItem = item.cloneNode(true);
        item.parentNode.replaceChild(newItem, item);
        
        // 添加新的事件监听器
        newItem.addEventListener('click', handleFileClick);
        newItem.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            e.stopPropagation();
            ipcRenderer.send('show-context-menu', {
                type: 'file',
                filePath: newItem.dataset.path,
                fileType: newItem.dataset.type
            });
        });
    });

    // 更新高亮显示
    updateFileHighlight();
}

// ===== 文件操作相关函数 =====
function handleFileClick(event) {
    event.preventDefault();
    event.stopPropagation();
    
    const fileItem = event.currentTarget;
    const filePath = fileItem.dataset.path;
    const fileType = fileItem.dataset.type;
    
    if (fileType === 'directory' || fileType === 'parent-dir') {
        currentPath = filePath;
        ipcRenderer.send('scan-directory', filePath);
        pathInput.value = filePath;
        return;
    }
    
    // 获取当前文件在过滤后列表中的索引
    currentFileIndex = filteredFiles.findIndex(f => f.path.replace(/\\/g, '/') === filePath);
    
    if (currentFileIndex !== -1) {
        showModal(filteredFiles[currentFileIndex]);
    }
}

function getPreviewableFiles(files) {
    return files.filter(file => {
        const type = getFileType(file.name);
        return type === 'video' || type === 'image';
    });
}
// 添加更新文件夹信息的函数
function updateFoldersInfo(paths) {
    if (paths.likePath && paths.deletePath) {
        currentFoldersInfo.innerHTML = `
            <div style="font-size: 14px; color: #64748b;padding:10px;box-sizing: border-box;">当前文件夹位置</div>
            <div class="folder-path">
                <span class="folder-path-label">Like文件夹:</span>
                <span class="folder-path-value">${paths.likePath}</span>
            </div>
            <div class="folder-path">
                <span class="folder-path-label">Delete文件夹:</span>
                <span class="folder-path-value">${paths.deletePath}</span>
            </div>
        `;
    } else {
        currentFoldersInfo.innerHTML = '<div style="color: #666; text-align: center;">尚未设置文件夹位置</div>';
    }
}
// ===== 对话框相关函数 =====
function showFileInfoDialog(info) {
    const modal = document.getElementById('fileInfoModal');
    const tableBody = document.getElementById('fileInfoTable');
    const closeBtn = modal.querySelector('.close');
    // 清空现有内容
    tableBody.innerHTML = '';

    // 添加信息行
    Object.entries(info).forEach(([key, value]) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${key}</td>
            <td>${value}</td>
        `;
        tableBody.appendChild(row);
    });

    // 显示模态框
    modal.style.display = 'flex';

    // 关闭按钮事件
    closeBtn.onclick = () => {
        modal.style.display = 'none';
    };

    // 点击模态框外部关闭
    window.onclick = (event) => {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    };
}
// 显示文件信息
async function showFileInfo(filePath) {
    try {
        const stats = await fs.promises.stat(filePath);
        const info = {
            '文件名': path.basename(filePath),
            '大小': formatFileSize(stats.size),
            '创建时间': formatDate(stats.birthtime),
            '修改时间': formatDate(stats.mtime),
            '访问时间': formatDate(stats.atime),
            '文件类型': getFileType(filePath),
            '完整路径': filePath
        };
        showFileInfoDialog(info);
    } catch (error) {
        alert('无法获取文件信息：' + error.message);
    }
}

// ===== 其他辅助函数 =====

// 在文件顶部的 IPC 监听器部分添加
ipcRenderer.on('path-copied', (event, path) => {
    // 显示提示消息
    showNotification(`路径已复制到剪贴板: ${path}`);
});

// 添加通知显示函数
function showNotification(message) {
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // 2秒后自动移除通知
    setTimeout(() => {
        notification.remove();
    }, 2000);
}

async function findDuplicateFiles() {
    if (!currentPath) {
        showNotification('请先选择一个文件夹', 'warning');
        return;
    }
    
    // 创建并显示进度对话框
    const progressModal = document.createElement('div');
    progressModal.className = 'modal progress-modal';
    progressModal.innerHTML = `
        <div class="modal-content">
            <h3>正在扫描文件...</h3>
            <div class="scan-progress">
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <div class="progress-text">准备扫描...</div>
            </div>
        </div>
    `;
    document.body.appendChild(progressModal);
    
    try {
        // 调用主进程进行扫描
        const result = await ipcRenderer.invoke('find-duplicates', currentPath);
        
        if (result.error) {
            showNotification(`扫描出错: ${result.error}`, 'error');
            return;
        }
        
        // 移除进度对话框
        progressModal.remove();
        
        // 显示重复文件对话框
        showDuplicatesDialog(result);
        
    } catch (error) {
        showNotification(`扫描出错: ${error.message}`, 'error');
    } finally {
        progressModal.remove();
    }
}

// 监听进度更新
ipcRenderer.on('scan-progress', (event, { current, total, status }) => {
    const progressBar = document.querySelector('.progress-modal .progress-fill');
    const progressText = document.querySelector('.progress-modal .progress-text');
    
    if (progressBar && progressText) {
        const percentage = Math.min((current / total) * 100, 100);
        progressBar.style.width = `${percentage}%`;
        progressText.textContent = `${status} ${current}/${total} (${percentage.toFixed(1)}%)`;
    }
});

// 监听扫描开始
ipcRenderer.on('scan-start', (event, { total }) => {
    const progressText = document.querySelector('.progress-modal .progress-text');
    if (progressText) {
        progressText.textContent = `开始扫描，共发现 ${total} 个项目`;
    }
});

// 监听扫描完成
ipcRenderer.on('scan-complete', (event, duplicates) => {
    showDuplicatesDialog(duplicates);
});

// 监听扫描错误
ipcRenderer.on('scan-error', (event, error) => {
    showNotification(`扫描出错: ${error}`, 'error');
});

// 添加进度对话框样式
const style = document.createElement('style');
style.textContent = `
.favorite-item,
.delete-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-bottom: 1px solid #eef2f7;
}

.remove-favorite,
.remove-delete {
    background: none;
    border: none;
    color: #64748b;
    font-size: 18px;
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.2s ease;
}

.remove-favorite:hover {
    color: #3498db;
    background: rgba(52, 152, 219, 0.1);
}

.remove-delete:hover {
    color: #ef4444;
    background: rgba(239, 68, 68, 0.1);
}

@media (prefers-color-scheme: dark) {
    .favorite-item,
    .delete-item {
        border-bottom-color: #334155;
    }
    
    .remove-favorite,
    .remove-delete {
        color: #94a3b8;
    }
    
    .remove-favorite:hover {
        background: rgba(52, 152, 219, 0.2);
    }
    
    .remove-delete:hover {
        background: rgba(239, 68, 68, 0.2);
    }
}
`;
document.head.appendChild(style);

// 显示重复文件对话框
function showDuplicatesDialog(duplicates) {
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'flex';
    
    const content = document.createElement('div');
    content.className = 'modal-content duplicates-modal';
    
    // 添加搜索框和批量操作按钮
    content.innerHTML = `
        <div class="modal-header">
            <div class="batch-actions">
                <button class="btn-select-all">全选</button>
                <button class="btn-invert-select">反选</button>
                <button class="btn-batch-favorite">批量收藏</button>
                <button class="btn-batch-delete">批量删除</button>
            </div>
            <h3>重复文件列表</h3>
            <span class="close">&times;</span>
        </div>
        <div class="search-container">
            <input type="text" class="search-input" placeholder="搜索文件名..." />
            <span class="search-count"></span>
        </div>
        <div class="duplicates-content">
            ${duplicates.length === 0 ? '<p>未找到重复文件</p>' : 
                duplicates.map(group => `
                    <div class="duplicate-group">
                        <div class="group-header">
                            <h4>基本名称: ${group.baseName}</h4>
                            <label class="group-checkbox">
                                <input type="checkbox" class="group-select-all" />
                                全选组
                            </label>
                        </div>
                        <div class="duplicate-files">
                            ${group.files.map(file => `
                                <div class="duplicate-file" data-path="${file.path}" data-name="${file.name.toLowerCase()}">
                                    <label class="file-checkbox">
                                        <input type="checkbox" class="file-select" />
                                    </label>
                                    <span class="file-name">${file.name}</span>
                                    <div class="file-info">
                                        <span>大小: ${formatFileSize(file.size)}</span>
                                        <span>修改时间: ${formatDate(file.mtime)}</span>
                                        <span>路径: ${file.path}</span>
                                    </div>
                                    <div class="file-actions">
                                        <button class="btn-favorite">添加到收藏</button>
                                        <button class="btn-delete">标记删除</button>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `).join('')
            }
        </div>
    `;
    
    modal.appendChild(content);
    document.body.appendChild(modal);

    // 关闭按钮事件
    const closeBtn = content.querySelector('.close');
    closeBtn.onclick = () => modal.remove();
    
    // 点击空白处关闭
    modal.onclick = (e) => {
        if (e.target === modal) modal.remove();
    };
    
    // 获取搜索相关元素
    const searchInput = content.querySelector('.search-input');
    const searchCount = content.querySelector('.search-count');
    const duplicateGroups = content.querySelectorAll('.duplicate-group');
    
    // 添加搜索功能
    let searchTimeout;
    searchInput.addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            const searchTerm = e.target.value.toLowerCase().trim();
            let matchCount = 0;
            
            duplicateGroups.forEach(group => {
                const files = group.querySelectorAll('.duplicate-file');
                let hasVisibleFiles = false;
                
                files.forEach(file => {
                    const fileName = file.dataset.name;
                    const isMatch = fileName.includes(searchTerm);
                    file.style.display = isMatch ? '' : 'none';
                    if (isMatch) {
                        matchCount++;
                        hasVisibleFiles = true;
                    }
                });
                
                // 如果组内没有匹配的文件，隐藏整个组
                group.style.display = hasVisibleFiles ? '' : 'none';
            });
            
            // 更新搜索结果计数
            searchCount.textContent = searchTerm ? 
                `找到 ${matchCount} 个匹配项` : '';
        }, 300); // 添加防抖
    });
    
    // 获取所有按钮
    const batchFavoriteBtn = content.querySelector('.btn-batch-favorite');
    const batchDeleteBtn = content.querySelector('.btn-batch-delete');
    const selectAllBtn = content.querySelector('.btn-select-all');
    const invertSelectBtn = content.querySelector('.btn-invert-select');

    // 批量收藏按钮事件
    batchFavoriteBtn.addEventListener('click', () => {
        const selectedFiles = getSelectedFiles(content);
        if (selectedFiles.length === 0) {
            showNotification('请先选择文件', 'warning');
            return;
        }

        // 遍历选中的文件并添加到收藏
        selectedFiles.forEach(file => {
            // 在对话框中标记为收藏
            const fileEl = content.querySelector(`.duplicate-file[data-path="${file.path.replace(/\\/g, '/')}"]`);
            if (fileEl) {
                fileEl.classList.add('marked-favorite');
            }
            
            // 在主界面中标记为收藏
            const mainFileEl = document.querySelector(`.file-item[data-path="${file.path.replace(/\\/g, '/')}"]`);
            if (mainFileEl) {
                mainFileEl.classList.add('marked-favorite');
            }
            
            // 添加到收藏列表
            if (!favoriteFiles.some(f => f.path === file.path)) {
                favoriteFiles.push(file);
            }
        });

        // 更新收藏列表并保存
        updateFavoriteList();
        ipcRenderer.send('update-favorites', favoriteFiles);
        showNotification(`已添加 ${selectedFiles.length} 个文件到收藏`, 'success');
    });

    // 批量删除按钮事件
    batchDeleteBtn.addEventListener('click', () => {
        const selectedFiles = getSelectedFiles(content);
        if (selectedFiles.length === 0) {
            showNotification('请先选择文件', 'warning');
            return;
        }

        // 遍历选中的文件并标记为删除
        selectedFiles.forEach(file => {
            // 在对话框中标记为删除
            const fileEl = content.querySelector(`.duplicate-file[data-path="${file.path.replace(/\\/g, '/')}"]`);
            if (fileEl) {
                fileEl.classList.add('marked-delete');
            }
            
            // 在主界面中标记为删除
            const mainFileEl = document.querySelector(`.file-item[data-path="${file.path.replace(/\\/g, '/')}"]`);
            if (mainFileEl) {
                mainFileEl.classList.add('marked-delete');
            }
            
            // 添加到删除列表
            if (!toDeleteFiles.some(f => f.path === file.path)) {
                toDeleteFiles.push(file);
            }
        });

        // 更新删除列表并保存
        updateDeleteList();
        ipcRenderer.send('update-to-delete', toDeleteFiles);
        showNotification(`已标记 ${selectedFiles.length} 个文件为删除`, 'success');
    });

    // 全选按钮事件
    selectAllBtn.addEventListener('click', () => {
        const checkboxes = content.querySelectorAll('.file-select');
        const shouldCheck = !Array.from(checkboxes).every(cb => cb.checked);
        checkboxes.forEach(cb => cb.checked = shouldCheck);
        updateGroupCheckboxes(content);
    });

    // 反选按钮事件
    invertSelectBtn.addEventListener('click', () => {
        const checkboxes = content.querySelectorAll('.file-select');
        checkboxes.forEach(cb => cb.checked = !cb.checked);
        updateGroupCheckboxes(content);
    });

    // 组内全选事件
    content.querySelectorAll('.group-select-all').forEach(checkbox => {
        checkbox.addEventListener('change', (e) => {
            const group = e.target.closest('.duplicate-group');
            const fileCheckboxes = group.querySelectorAll('.file-select');
            fileCheckboxes.forEach(cb => cb.checked = e.target.checked);
        });
    });

    // 单个文件的收藏和删除按钮事件
    content.querySelectorAll('.duplicate-file').forEach(fileEl => {
        const filePath = fileEl.dataset.path;
        const fileName = fileEl.querySelector('.file-name').textContent;
        const fileInfo = {
            name: fileName,
            path: filePath,
            // 添加其他必要的文件信息
            size: fileEl.querySelector('.file-info').textContent.match(/大小: (.*?)\s/)?.[1] || '',
            mtime: new Date(fileEl.querySelector('.file-info').textContent.match(/修改时间: (.*?)\s/)?.[1] || ''),
        };
    
        // 收藏按钮事件
        fileEl.querySelector('.btn-favorite').addEventListener('click', () => {
            fileEl.classList.add('marked-favorite');
            const mainFileEl = document.querySelector(`.file-item[data-path="${filePath.replace(/\\/g, '/')}"]`);
            if (mainFileEl) {
                mainFileEl.classList.add('marked-favorite');
            }
            
            if (!favoriteFiles.some(f => f.path === filePath)) {
                favoriteFiles.push(fileInfo);
                updateFavoriteList();
                ipcRenderer.send('update-favorites', favoriteFiles);
            }
            showNotification('已添加到收藏', 'success');
        });
    
        // 删除按钮事件
        fileEl.querySelector('.btn-delete').addEventListener('click', () => {
            fileEl.classList.add('marked-delete');
            const mainFileEl = document.querySelector(`.file-item[data-path="${filePath.replace(/\\/g, '/')}"]`);
            if (mainFileEl) {
                mainFileEl.classList.add('marked-delete');
            }
            
            if (!toDeleteFiles.some(f => f.path === filePath)) {
                toDeleteFiles.push(fileInfo);
                updateDeleteList();
                ipcRenderer.send('update-to-delete', toDeleteFiles);
            }
            showNotification('已标记为删除', 'success');
        });
    });
    

    // 文件选择框变化事件
    content.querySelectorAll('.file-select').forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            updateGroupCheckboxes(content);
        });
    });
}
// 辅助函数：获取选中的文件
function getSelectedFiles(content) {
    const selectedFiles = [];
    content.querySelectorAll('.file-select:checked').forEach(checkbox => {
        const fileEl = checkbox.closest('.duplicate-file');
        if (fileEl) {
            const filePath = fileEl.dataset.path;
            const fileName = fileEl.querySelector('.file-name').textContent;
            const fileInfo = {
                name: fileName,
                path: filePath,
                // 添加其他必要的文件信息
                size: fileEl.querySelector('.file-info').textContent.match(/大小: (.*?)\s/)?.[1] || '',
                mtime: new Date(fileEl.querySelector('.file-info').textContent.match(/修改时间: (.*?)\s/)?.[1] || ''),
            };
            selectedFiles.push(fileInfo);
        }
    });
    return selectedFiles;
}

// 辅助函数：更新组选择框状态
function updateGroupCheckboxes(content) {
    content.querySelectorAll('.duplicate-group').forEach(group => {
        const groupCheckbox = group.querySelector('.group-select-all');
        const fileCheckboxes = Array.from(group.querySelectorAll('.file-select'));
        const checkedCount = fileCheckboxes.filter(cb => cb.checked).length;
        
        if (groupCheckbox) {
            groupCheckbox.checked = checkedCount === fileCheckboxes.length;
            groupCheckbox.indeterminate = checkedCount > 0 && checkedCount < fileCheckboxes.length;
        }
    });
}

// 添加到收藏列表
function addToFavorites(file) {
    // 检查是否已经存在
    if (!favoriteFiles.some(f => f.path === file.path)) {
        favoriteFiles.push(file);
        updateFavoriteList();
        
        // 添加高亮样式到文件项
        const fileElement = document.querySelector(`.file-item[data-path="${file.path.replace(/\\/g, '/')}"]`);
        if (fileElement) {
            fileElement.classList.add('marked-favorite');
        }
        
        // 保存到 store
        ipcRenderer.send('update-favorites', favoriteFiles);
    }
}

// 添加到删除列表
function addToDeleteList(file) {
    // 检查是否已经存在
    if (!toDeleteFiles.some(f => f.path === file.path)) {
        toDeleteFiles.push(file);
        updateDeleteList();
        
        // 添加高亮样式到文件项
        const fileElement = document.querySelector(`.file-item[data-path="${file.path.replace(/\\/g, '/')}"]`);
        if (fileElement) {
            fileElement.classList.add('marked-delete');
        }
        
        // 保存到 store
        ipcRenderer.send('update-to-delete', toDeleteFiles);
    }
}

// 监听查找重复文件的事件
ipcRenderer.on('find-duplicates', () => {
    if (!allFiles || allFiles.length === 0) {
        showNotification('请先扫描文件夹', 'warning');
        return;
    }
    
    const duplicates = findDuplicateFiles(allFiles);
    showDuplicatesDialog(duplicates);
});
